package com.atguigu.flink.chapter02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 流处理 - 有界流
 *
 * @author cjp
 * @version 1.0
 * @date 2021/1/18 11:22
 */
public class Flink03_WC_BoundedStream {
    public static void main(String[] args) throws Exception {
        // 1. 创建流式的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 2. 读取数据
        DataStreamSource<String> inputDS = env.readTextFile("input/word.txt");

        // 3. 处理数据、输出
        inputDS
                .flatMap(new FlatMapFunction<String, String>() {
                    @Override
                    public void flatMap(String value, Collector<String> out) throws Exception {
                        // 切分
                        String[] words = value.split(" ");
                        for (String word : words) {
                            // 通过采集器，往下游发送 word
                            out.collect(word);
                        }
                    }
                })
                .map(new MapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> map(String value) throws Exception {
                        return Tuple2.of(value, 1L);
                    }
                })
                .keyBy(0)
                .sum(1)
                .print();

        // 4. 执行
        env.execute();
    }
}


/**
 * 与批处理的区别：
 * 1. 执行环境的类不一样
 * 2. 分组使用的算子不一样：groupby、keyby
 * 3. 流处理需要 启动
 */
